package demo01Array;

import org.junit.Test;

import java.util.ArrayList;

/**
 * @ClassName $ {NAME}
 * @Description TODO
 * @Author 沈新源
 * @Date $ {DATE} $ {TIME}
 * @Version 1. 0
 **/

public class MatrixClockwise {
    int[][] arr = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16}
    };

    int[][] b = {{1}, {2}, {3}, {4}, {5}};

    int[][] c = {{1, 2, 3, 4, 5}};

    //顺时针打印矩阵：[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
    public ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList();
        int x = matrix.length, y = matrix[0].length;

        int i = 0, j = 0;       //控制顺时针打印的下标
        int tmp = 0;           //控制边界
        int total = 0;        //存储已经打印的数字个数

        result.add(matrix[i][j]);
        total++;
        while (true) {        //结束条件
            while (j < y - 1 - tmp) {
                j++;
                total++;
                result.add(matrix[i][j]);
            }
            if (total == x * y) break;

            while (i < x - 1 - tmp) {
                i++;
                total++;
                result.add(matrix[i][j]);
            }
            if (total == x * y) break;

            while (j > tmp) {
                j--;
                total++;
                result.add(matrix[i][j]);
            }
            if (total == x * y) break;

            while (i > tmp + 1) {
                i--;
                result.add(matrix[i][j]);
                total++;
            }
            if (total == x * y) break;
            tmp++;
        }
        return result;
    }

    @Test
    public void test() {
        //
        System.out.println("printMatrix(arr) = " + printMatrix(arr));
        System.out.println("printMatrix(b) = " + printMatrix(b));
        System.out.println("printMatrix(c) = " + printMatrix(c));
    }
}
